﻿using System;
using System.Web.UI;
using System.Text;
using System.Collections.Generic;

namespace wpdotnet.Controls
{
    /// <summary>
    /// Display a menu control
    /// <%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %>
    /// </summary>
    public class WpMenu:WpControl
    {
        

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(GetMenu());
        }

        private string GetMenu()
        {
            StringBuilder menu = new StringBuilder();
            if (string.IsNullOrEmpty(CssClass))
            {
                menu.AppendLine("<ul>");
            }
            else 
            {
                menu.AppendFormat("<ul class=\"{0}\">",CssClass);
                menu.AppendLine();
            }

            List<DAL.MenuItem> menuItems = GetMenuItems();
            if (menuItems != null)
            {
                foreach (DAL.MenuItem item in menuItems)
                {
                    menu.AppendFormat("<li><a href=\"{0}\">{1}</a></li>",item.Url,item.Title);
                    menu.AppendLine();
                }
            }
            else 
            {
                menu.AppendLine("<li>An error occured while rendering the menu.</li>"); 
            }
            menu.AppendLine("</ul>"); 
            return menu.ToString();
        }

        private List<DAL.MenuItem> GetMenuItems()
        {
            if (IsCacheEnabled)
            {
                if (CacheManager.Contains(_cacheKey))
                {
                    return CacheManager.Get<List<DAL.MenuItem>>(_cacheKey);
                }
            }

            List<DAL.MenuItem> menu = WpManager.GetMenu();
            
            if (menu != null)
            {
                if (IsCacheEnabled)
                {
                    CacheManager.Insert(_cacheKey, menu);
                }
            }
            
            return menu;
           
        }
    }
}
